import type Taro from '@tarojs/taro'

declare type RequestTask = ReturnType<typeof Taro.request>

class Canceler {
  private requestMap: Map<string, RequestTask>

  constructor() {
    this.requestMap = new Map<string, RequestTask>()
  }

  add(uniqueKey: string, request: RequestTask) {
    this.remove(uniqueKey)
    if (!this.requestMap.has(uniqueKey))
      this.requestMap.set(uniqueKey, request)
  }

  delete(uniqueKey: string) {
    if (this.requestMap.has(uniqueKey))
      this.requestMap.delete(uniqueKey)
  }

  remove(uniqueKey: string) {
    if (this.requestMap.has(uniqueKey)) {
      const request = this.requestMap.get(uniqueKey)
      if (request && request.abort)
        request.abort()

      this.delete(uniqueKey)
    }
  }

  removeAll() {
    this.requestMap.forEach((request) => {
      if (request && request.abort)
        request.abort()
    })

    this.requestMap.clear()
  }

  reset() {
    this.requestMap = new Map<string, RequestTask>()
  }
}

export default new Canceler()

